package com.applozic.mobicomkit.uiwidgets.conversation.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.app.FragmentActivity;
import android.text.style.TextAppearanceSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.applozic.mobicomkit.api.attachment.FileClientService;
import com.applozic.mobicomkit.api.conversation.Message;
import com.applozic.mobicomkit.api.conversation.MobiComConversationService;
import com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService;
import com.applozic.mobicomkit.contact.AppContactService;
import com.applozic.mobicomkit.contact.BaseContactService;
import com.applozic.mobicomkit.uiwidgets.AlCustomizationSettings;
import com.applozic.mobicomkit.uiwidgets.conversation.view.ApplozicCallView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.ApplozicChannelCustomMessageView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.ApplozicCustomMessageView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.CustomReceivedMessageView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.CustomSendMessageView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.GetRedPacketResponseView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.GivePrizeLeftView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.GivePrizeRIghtView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.MobicomDateView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.MobicomReceivedMessageView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.MobicomSendMessageView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.RedPacketLeftView;
import com.applozic.mobicomkit.uiwidgets.conversation.view.RedPacketRightView;
import com.applozic.mobicommons.commons.image.ImageCache;
import com.applozic.mobicommons.commons.image.ImageLoader;
import com.applozic.mobicommons.commons.image.ImageUtils;
import com.applozic.mobicommons.emoticon.EmojiconHandler;
import com.applozic.mobicommons.people.channel.Channel;
import com.applozic.mobicommons.people.contact.Contact;
import com.lottery.ruok.lottrey.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by adarsh on 4/7/15.
 */
public class DetailedConversationAdapter extends ArrayAdapter<Message> {
    public ImageLoader contactImageLoader, loadImage;
    public String searchString;
    AlCustomizationSettings alCustomizationSettings;
    private Context context;
    private Contact contact;
    private Channel channel;
    private boolean individual;
    private ImageLoader imageThumbnailLoader;
    private EmojiconHandler emojiconHandler;
    private FileClientService fileClientService;
    private MessageDatabaseService messageDatabaseService;
    private BaseContactService contactService;
    private Class<?> messageIntentClass;
    private List<Message> messageList;
    private List<Message> originalList;
    private MobiComConversationService conversationService;
    private ImageCache imageCache;
    private TextAppearanceSpan highlightTextSpan;


    public DetailedConversationAdapter(final Context context, int textViewResourceId, List<Message> messageList, Channel channel, Class messageIntentClass, EmojiconHandler emojiconHandler) {
        this(context, textViewResourceId, messageList, null, channel, messageIntentClass, emojiconHandler);
    }

    public DetailedConversationAdapter(final Context context, int textViewResourceId, List<Message> messageList, Contact contact, Class messageIntentClass, EmojiconHandler emojiconHandler) {
        this(context, textViewResourceId, messageList, contact, null, messageIntentClass, emojiconHandler);
    }

    public DetailedConversationAdapter(final Context context, int textViewResourceId, List<Message> messageList, final Contact contact, Channel channel, Class messageIntentClass, EmojiconHandler emojiconHandler) {
        super(context, textViewResourceId, messageList);
        this.messageIntentClass = messageIntentClass;
        this.context = context;
        this.contact = contact;
        this.channel = channel;
        this.emojiconHandler = emojiconHandler;
        this.individual = (contact != null || channel != null);
        this.fileClientService = new FileClientService(context);
        this.messageDatabaseService = new MessageDatabaseService(context);
        this.conversationService = new MobiComConversationService(context);
        this.contactService = new AppContactService(context);
        this.imageCache = ImageCache.getInstance(((FragmentActivity) context).getSupportFragmentManager(), 0.1f);
        this.messageList = messageList;
        contactImageLoader = new ImageLoader(getContext(), ImageUtils.getLargestScreenDimension((Activity) getContext())) {
            @Override
            protected Bitmap processBitmap(Object data) {
                return contactService.downloadContactImage(getContext(), (Contact) data);
            }
        };
        contactImageLoader.setLoadingImage(R.drawable.applozic_ic_contact_picture_180_holo_light);
        contactImageLoader.addImageCache(((FragmentActivity) context).getSupportFragmentManager(), 0.1f);
        contactImageLoader.setImageFadeIn(false);

        loadImage = new ImageLoader(getContext(), ImageUtils.getLargestScreenDimension((Activity) getContext())) {
            @Override
            protected Bitmap processBitmap(Object data) {
                return fileClientService.loadMessageImage(getContext(), (String) data);
            }
        };
        loadImage.setImageFadeIn(false);
        loadImage.addImageCache(((FragmentActivity) context).getSupportFragmentManager(), 0.1f);
        imageThumbnailLoader = new ImageLoader(getContext(), ImageUtils.getLargestScreenDimension((Activity) getContext())) {
            @Override
            protected Bitmap processBitmap(Object data) {
                return fileClientService.loadThumbnailImage(getContext(), (Message) data, getImageLayoutParam(false).width, getImageLayoutParam(false).height);
            }
        };
        imageThumbnailLoader.setImageFadeIn(false);
        imageThumbnailLoader.addImageCache(((FragmentActivity) context).getSupportFragmentManager(), 0.1f);
        highlightTextSpan = new TextAppearanceSpan(context, R.style.searchTextHiglight);
    }

    public void setAlCustomizationSettings(AlCustomizationSettings alCustomizationSettings) {
        this.alCustomizationSettings = alCustomizationSettings;
    }


    public View getView(int position, View convertView, ViewGroup parent) {
        View customView;
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final Message message = getItem(position);
        final int type = getItemViewType(position);
        switch (type) {
            case 2:
                MobicomDateView mobicomDateView;
                if (convertView == null) {
                    mobicomDateView = new MobicomDateView(context);
                } else {
                    mobicomDateView = (MobicomDateView) convertView;
                }
                mobicomDateView.setData(message, alCustomizationSettings);

                return mobicomDateView;
            case 3:
                ApplozicCustomMessageView applozicCustomMessageView;
                if (convertView == null) {
                    applozicCustomMessageView = new ApplozicCustomMessageView(context);
                } else {
                    applozicCustomMessageView = (ApplozicCustomMessageView) convertView;
                }
                applozicCustomMessageView.setData(message);

                return applozicCustomMessageView;
            case 4:
                ApplozicChannelCustomMessageView applozicChannelCustomMessageView;
                if (convertView == null) {
                    applozicChannelCustomMessageView = new ApplozicChannelCustomMessageView(context);
                } else {
                    applozicChannelCustomMessageView = (ApplozicChannelCustomMessageView) convertView;
                }
                applozicChannelCustomMessageView.setData(message);

                return applozicChannelCustomMessageView;
            case 5:
                ApplozicCallView applozicCallView;

                if (convertView == null) {
                    applozicCallView = new ApplozicCallView(context);
                } else {
                    applozicCallView = (ApplozicCallView) convertView;
                }
                applozicCallView.setData(message);
                return applozicCallView;


            case 6://普通消息收
                CustomSendMessageView customSendMessageView;
                if (convertView == null) {
                    customSendMessageView = new CustomSendMessageView(context);
                } else {
                    customSendMessageView = (CustomSendMessageView) convertView;
                }
                customSendMessageView.setData(message, contactService, emojiconHandler);
                return customSendMessageView;
            case 7://普通消息 发
                CustomReceivedMessageView customReceivedMessageView;
                if (convertView == null) {
                    customReceivedMessageView = new CustomReceivedMessageView(context);
                } else {
                    customReceivedMessageView = (CustomReceivedMessageView) convertView;
                }
                customReceivedMessageView.setData(message, emojiconHandler);
                return customReceivedMessageView;
            case 8://红包领取通知
                GetRedPacketResponseView getRedPacketResponseView;

                if (convertView == null) {
                    getRedPacketResponseView = new GetRedPacketResponseView(context);
                } else {

                    getRedPacketResponseView = (GetRedPacketResponseView) convertView;
                }
                getRedPacketResponseView.setData(message, contactService);
                return getRedPacketResponseView;
            case 9://打赏消息 收
                GivePrizeLeftView givePrizeLeftView;
                if (convertView == null) {
                    givePrizeLeftView = new GivePrizeLeftView(context);
                } else {
                    givePrizeLeftView = (GivePrizeLeftView) convertView;
                }
                givePrizeLeftView.setData(message, contactService);
                return givePrizeLeftView;
            case 10://打赏消息 发
                GivePrizeRIghtView givePrizeRIghtView;
                if (convertView == null) {
                    givePrizeRIghtView = new GivePrizeRIghtView(context);
                } else {
                    givePrizeRIghtView = (GivePrizeRIghtView) convertView;
                }
                givePrizeRIghtView.setData(message, contactService);
                return givePrizeRIghtView;
            case 11://红包消息 收
                RedPacketLeftView redPacketLeftView;
                if (convertView == null) {
                    redPacketLeftView = new RedPacketLeftView(context);
                } else {
                    redPacketLeftView = (RedPacketLeftView) convertView;
                }
                redPacketLeftView.setData(message, contactService);
                return redPacketLeftView;
            case 12://红包消息 发
                RedPacketRightView redPacketRightView;
                if (convertView == null) {
                    redPacketRightView = new RedPacketRightView(context);
                } else {
                    redPacketRightView = (RedPacketRightView) convertView;
                }
                redPacketRightView.setData(message, contactService);
                return redPacketRightView;
            case 0:
                MobicomReceivedMessageView mobicomReceivedMessageView;
//                if (convertView == null) {
//                    mobicomReceivedMessageView = new MobicomReceivedMessageView(getContext());
//                } else {
//                    mobicomReceivedMessageView = (MobicomReceivedMessageView) convertView;
//        }
                mobicomReceivedMessageView = new MobicomReceivedMessageView(getContext());
                mobicomReceivedMessageView.setData(message, contactService, individual, contact, channel, alCustomizationSettings, imageCache, fileClientService, imageThumbnailLoader, messageDatabaseService, conversationService, messageIntentClass, loadImage, emojiconHandler, searchString, highlightTextSpan);
                return mobicomReceivedMessageView;
            case 1:
                MobicomSendMessageView mobicomSendMessageView;
//                if (convertView == null) {
//                    mobicomSendMessageView = new MobicomSendMessageView(getContext());
//                } else {
//                    mobicomSendMessageView = (MobicomSendMessageView) convertView;
//                }
                mobicomSendMessageView = new MobicomSendMessageView(getContext());
                mobicomSendMessageView.setData(message, contactService, individual, contact, channel, alCustomizationSettings, imageCache, fileClientService, imageThumbnailLoader, messageDatabaseService, conversationService, messageIntentClass, loadImage, emojiconHandler, searchString, highlightTextSpan);
                return mobicomSendMessageView;
        }

        return new

                View(context);

    }


    @Override
    public int getViewTypeCount() {
        return 13;
    }

    @Override
    public int getItemViewType(int position) {
        Message message = getItem(position);
        if (message == null) {
            return 0;
        }
        if (message.isTempDateType()) {
            return 2;
        }
        if (message.isCustom()) {
            return 3;
        }
        if (message.isChannelCustomMessage()) {
            return 4;
        }
        if (message.isVideoCallMessage()) {
            return 5;
        }
        if (message.getContentType() == Message.ContentType.DEFAULT.getValue()) {
            if (message.isTypeOutbox()) {
                //1发送
                return 7;
            } else {
                //接受
                return 6;
            }
        }
        if (message.getContentType() == Message.ContentType.RED_PACKET_RESPONSE.getValue()) {
            return 8;//红包领取通知
        }
        if (message.getContentType() == Message.ContentType.GIVE_PRIZE.getValue()) {
            if (message.isTypeOutbox()) {
                //大赏消息发送
                return 10;
            } else {
                //大赏消息接受
                return 9;
            }
        }
        if (message.getContentType() == Message.ContentType.RED_PACKET.getValue()) {
            if (message.isTypeOutbox()) {
                //红包消息发送
                return 12;
            } else {
                //红包消息接受
                return 11;
            }
        }
        return message.isTypeOutbox() ? 1 : 0;
    }

    public ViewGroup.LayoutParams getImageLayoutParam(boolean outBoxType) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, context.getResources().getDisplayMetrics());
        ViewGroup.MarginLayoutParams params;
        if (outBoxType) {
            params = new RelativeLayout.LayoutParams(metrics.widthPixels + (int) wt_px * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins((int) wt_px, 0, (int) wt_px, 0);
        } else {
            params = new LinearLayout.LayoutParams(metrics.widthPixels - (int) wt_px * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 0);

        }
        return params;
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                final FilterResults oReturn = new FilterResults();
                final List<Message> results = new ArrayList<>();
                if (originalList == null)
                    originalList = messageList;
                if (constraint != null) {
                    searchString = constraint.toString();
                    if (originalList != null && originalList.size() > 0) {
                        for (final Message message : originalList) {
                            if (message.getMessage().toLowerCase()
                                    .contains(constraint.toString())) {
                                results.add(message);


                            }
                        }
                    }
                    oReturn.values = results;
                } else {
                    oReturn.values = originalList;
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                messageList = (ArrayList<Message>) results.values;
                notifyDataSetChanged();
            }
        };
    }


    public void refreshContactData() {
        if (contact != null) {
            contact = contactService.getContactById(contact.getContactIds());
        }
    }

    public void setData(List<Message> messageList) {
        this.messageList = messageList;
        notifyDataSetChanged();
    }
}